package com.kalvan.web.servlet.request;

import com.kalvan.core.exception.BizException;
import com.kalvan.web.servlet.annotation.ParamsDecrypted;
import com.kalvan.web.servlet.interceptor.DecryptInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 统一请求数据扩展
 *
 * @author chenliang
 */
@RestController
@ControllerAdvice
@Slf4j
public class RequestHandler implements RequestBodyAdvice {
    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        binder.registerCustomEditor(
                Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getMethodAnnotation(ParamsDecrypted.class) != null) {
            return true;
        }
        return false;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        try {
            InputStream body = httpInputMessage.getBody();
            String encryptParams = IOUtils.toString(body, "UTF-8");
            HttpHeaders httpHeaders = httpInputMessage.getHeaders();
            List<String> key = httpHeaders.get("key");
            if (key == null || key.size() == 0) {
                throw new BizException("解密密钥不存在");
            }
            String params = DecryptInterceptor.decryptParam(key.get(0), encryptParams);
            if (params == null) {
                log.error("解密失败:  key:{} encryptParams:{}", key.get(0), encryptParams);
                throw new BizException("解密失败");
            }
            /**
             * 构建新的httpInputMessage
             */
            return new HttpInputMessage() {
                @Override
                public HttpHeaders getHeaders() {
                    return httpInputMessage.getHeaders();
                }

                @Override
                public InputStream getBody() {
                    return IOUtils.toInputStream(params);
                }
            };
        } catch (IOException e) {
            log.error("RequestBodyAdvice获取InputStream失败");
        }
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
